module.exports = app => {
	const express = require('express');
	const router = express.Router();
	const assert = require('http-assert');
	const jwt = require('jsonwebtoken');
	const multer  = require('multer');

	function randomString(len) {
	　　len = len || 32;
	　　let $chars = 'ABCDEFGHJKLMNOPQRSTUVWXYZabcdegfhijklmnoprstuvwxyz12345678';    /*默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1*/
	　　let maxPos = $chars.length;
	　　let pwd = '';
	　　for (i = 0; i < len; i++) {
	　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	　　}
	　　return pwd;
	}

	function timestampToTime(timestamp) {
	  	let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	  	let Y = date.getFullYear() + '-';
	  	let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	  	let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
	  	let H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() ;
	  	let MI = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() ;
	  	let S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds() ;
	  	return Y + M + D+'_'+ H + "." + MI + "." + S;
	}
	
	// 获取资源列表
	router.get('/', async (req, res) => {
		const result=await req.Service.getList(req.query,req.userId);
		res.json(result);
	})
	// 获取资源详情
	.get('/:name', async (req, res) => {
		let name=req.params.name;
		const result=await req.Service[name](req.userId);
		res.json(result);
	})
	// 创建资源
	.post('/', async (req, res) => {		
		req.body.id=randomString(24);
	 	const result = await req.Service.byCreate(req.body,req.userId);
	 	if(result.affectedRows>0) return res.json({success:true});
		else res.json({success:false});
	})
	// 创建资源详情
	.post('/:name', async (req, res) => {
		let name=req.params.name;
		req.body.imgId=randomString(24);
	 	const result = await req.Service[name](req.body,req.userId);
	 	if(result.affectedRows>0) return res.json({success:true});
		else return res.json({success:false});
	})
	// 更新资源
	.put('/', async (req, res) => {
		const result = await req.Service.byUpdate(req.body,req.userId);
		console.log(result);
		assert(result.affectedRows,403,'你没有权限修改');
		res.json({success:true});
	})
	// 更新资源详情
	.put('/:name', async (req, res) => {
		let name=req.params.name;
		const result=await req.Service[name](req.userId,req.body);
		assert(result.affectedRows,403,'你没有权限修改');
		res.json({success:true});
	})
	// 删除资源
	.delete('/', async (req, res) => {
		const result = await req.Service.byDelete(req.body,req.userId);
		assert(result.affectedRows,403,'你没有权限删除');
		res.json({success:true});  
	})

	//上传用户头像
	let setParams = multer.diskStorage({
	  	destination: function (req, file, callback) {
	    	callback(null, "./avator");
	  	},
	  	filename: function (req, file, callback) {
		    let time=timestampToTime(new Date().getTime());
		    let fileName=time+'-'+file.originalname;
		    file.originalname='http://localhost:2008/avator/'+fileName;
		    callback(null,fileName); 
	  	}	
	});
	const avator = multer({ storage: setParams }).single("file"); 
	router.post('/avator',avator,async function(req, res, next){
	  	let userId=req.body.userId;
	  	let imgPath=req.file.originalname;
	  	let sql=`update user set avator=? where id=?`;
	  	let result = await db(sql,[imgPath,userId]);
	  	res.json({ imgPath:imgPath });
	})

	// 上传图片，存放到本地文件夹
	let imageList=[];
	let Storage = multer.diskStorage({
		destination: function (req, file, callback) {
			callback(null, "./images");
		},
		filename: function (req, file, callback) {
			let d=timestampToTime(new Date().getTime());
			let fname=d+'—'+file.originalname;
			fileName='http://localhost:2008/images/'+fname;
			imageList.push(fileName); 
			callback(null,fname); 
		}
	});
	let upload = multer({ storage: Storage }).array("file",3); 
	router.post("/uploadToLocal",upload, function (req, res) {
		res.json({ imgpath:imageList });
		imageList=[];
	})
	const authMiddleware = require('../../middleware/auth')
	const resourceMiddleware = require('../../middleware/resource');
	app.use('/api/:resource',authMiddleware(),resourceMiddleware(), router);
}